/****************************************************************************
 Copyright (c) 2017-2020 SuperSuRaccoon
 
 Site: http://www.supersuraccoon-cocos2d.com
 Mail: supersuraccoon@gmail.com

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/
 
/**
 * @classdesc The component for rendering sight area with mask effect (using cc.ClippingNode).
    JSBinding Support [○]
    JSBinding Functions Support:
        addTarget
        removeTarget
        removeTargets
        removeAllTargets
        updateTarget
        updateTargets
 * @class
 * @extends cc.Node
 * @prop {cc.LayerColor}                       maskLayer                        - A color layer for mask effect.
 * @prop {cc.Node}                             maskStencilNode                  - Mask stencilNode container.
 * @prop {cc.ClippingNode}                     maskClipper                      - The cc.ClippingNode instance.
 * @prop {Array.<cc.Node>}                     targets                          - The targets whoses sight area will be rendered for mask effect.
 * @prop {Array.<losComponentCoreProvider>}    losComponentCoreProviders        - Functions for providing ssr.LoS.Component.Core instance for each target node.
 * @prop {Array.<cc.DrawNode>}                 maskRenders                      - The stencil render, one per target node.
 */
ssr.LoS.Component.Shadow = cc.Node.extend( /** @lends ssr.LoS.Component.Mask# */ {
    /**
     * The constructor
     * @function
     */
    ctor:function(losCoreObject, obstacleObject, configurations) {
        this._super();
        if(!cc.sys.isNative && cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
            cc.assert(0, "ssr.LoS.Component.Mask can only be used in WEBGL mode!")
            return;
        }
        //
        this._cullingObstacleObjects = [];
        this._obstacleObject = obstacleObject;
        this._losCoreObject = losCoreObject;
        this._losComponentCore = new ssr.LoS.Component.Core(losCoreObject);
        this._losComponentCore.addObstacle(obstacleObject, obstacleObject.getVertexArray());
        //
        this._configurations = configurations || {};
        //
        this._maskColor = this._configurations["color"] || cc.color.BLACK;
        this._maskStencilNode = new cc.Node();
        this._maskClipper = new cc.ClippingNode();
        this._maskClipper.setInverted(true);
        this._maskClipper.stencil = this._maskStencilNode;
        this.addChild(this._maskClipper);
        //
        if (this._configurations["cullingObstacles"]) {
            for (var i = this._configurations["cullingObstacles"].length - 1; i >= 0; i--) {
                this.addCullingObstacle(this._configurations["cullingObstacles"][i]);
            }
        }
        //
        if (this._configurations["texture"]) {
            this._configurations["scale"] = this._configurations["scale"] ? this._configurations["scale"] : 1;
            this._maskLayer = new cc.Sprite(this._configurations["texture"]);
            this._maskLayer.setScale(this._configurations["scale"]);
            this._maskLayer.setColor(this._maskColor);
        }
        else {
            this._configurations["radius"] = this._configurations["radius"] ? this._configurations["radius"] : 100;
            this._maskLayer = new ssr.LoS.Component.ShadowMask(this._maskColor, this._configurations["radius"] || 100);
        }
        this._maskClipper.addChild(this._maskLayer);
        //
        this._maskRender = new cc.DrawNode();
        this._maskStencilNode.addChild(this._maskRender);
    },
    setColor:function(color) {
        this._maskColor = color;
        this._maskLayer.setColor(color);
    },
    getColor:function(color) {
        return this._maskColor;
    },
    setRadius:function(radius) {
        if (this._configurations["texture"]) {
            return;
        }
        this._configurations["radius"] = radius;
        this._maskLayer.setRadius(radius);
    },
    getRadius:function() {
        return this._configurations["radius"];
    },
    setScale:function(scale) {
        if (!this._configurations["texture"]) {
            return;
        }
        this._configurations["scale"] = scale;
        this._maskLayer.setContentSize(radius, radius);
    },
    getScale:function() {
        return this._configurations["scale"];
    },
    enableTexture:function(texturePng) {
        this._configurations["texture"] = texturePng;
        this._configurations["scale"] = this._configurations["scale"] ? this._configurations["scale"] : 1;
        this._maskLayer.removeFromParent(true);
        this._maskLayer = new cc.Sprite(this._configurations["texture"]);
        this._maskLayer.setScale(this._configurations["scale"]);
        this._maskLayer.setColor(this._maskColor);
        this._maskClipper.addChild(this._maskLayer);
    },
    disableTexture:function(texturePng) {
        this._configurations["texture"] = null;
        this._configurations["radius"] = this._configurations["radius"] ? this._configurations["radius"] : 100;
        this._maskLayer.removeFromParent(true);
        this._maskLayer = new ssr.LoS.Component.ShadowMask(this._maskColor, this._configurations["radius"] || 100);
        this._maskClipper.addChild(this._maskLayer);
    },
    enableDynamic:function() {
        this._configurations["dynamic"] = true;
    },
    disableDynamic:function(texturePng) {
        this._configurations["dynamic"] = false;
    },
    clearCullingObstacles:function() {
        this._cullingObstacleObjects = [];
    },
    addCullingObstacles:function(obstacleObjectArray) {
        for (var i = obstacleObjectArray.length - 1; i >= 0; i--) {
            this.addCullingObstacle(obstacleObjectArray[i]);
        }
    },
    addCullingObstacle:function(obstacleObject) {
        this._cullingObstacleObjects.push(obstacleObject);
    },
    getCullingObstacles:function() {
        return this._cullingObstacleObjects;
    },
    /**
     * Update the target's sight area mask effect.
     * @function
     * @param {cc.Node} node The target whose sight area to be updated.
     * @param {Boolean} [needForceUpdate=false] If need to update the target's sight area no matter it is changed or not.
     */
    update:function(isForceLoSUpdate) {
        var render = this._maskRender;
        var losComponentCore = this._losComponentCore;
        losComponentCore.update();
        if (losComponentCore.isUpdated() || isForceLoSUpdate) {
            render.clear();
            //
            var sightAreaArray = losComponentCore.getSightArea();
            var sourcePosition = losComponentCore.getPosition();
            var screenPosition = losComponentCore.getOwnerScreenPosition();
            //
            if (this._configurations["dynamic"]) {
                var dist = cc.pDistance(screenPosition, this.getParent().convertToWorldSpace());
                if (this._configurations["min"] && dist < this._configurations["min"]) {
                    dist = this._configurations["min"];
                }
                else if (this._configurations["max"] && dist > this._configurations["max"]) {
                    dist = this._configurations["max"];
                }
                if (this._maskLayer instanceof cc.Layer) {
                    this._maskLayer.setRadius(dist);
                }
                else {
                    this._maskLayer.setScale(dist / this._maskLayer.width * this._configurations["scale"]);
                }
            }
            for (var i = 0, l = sightAreaArray.length; i < l; i ++) {
                var toDrawPoly = sightAreaArray[i].slice();
                if (losComponentCore.getMode() == ssr.LoS.Constant.MODE.UNLIMITED_RANGE) {
                    toDrawPoly.push(sourcePosition);
                }
                else if (losComponentCore.getMode() == ssr.LoS.Constant.MODE.LIMITED_RANGE_WITH_FULL_ANGLE) {
                    if (l > 1) {
                        toDrawPoly.push(sourcePosition);
                    }
                }
                else {
                    toDrawPoly.push(sourcePosition);
                }
                for (var j = 0, ll = toDrawPoly.length; j < ll; j ++) {
                    toDrawPoly[j] = cc.pSub(toDrawPoly[j], this._obstacleObject.getPosition());
                }
                render.drawPoly(toDrawPoly, ssr.LoS.Constant.RENDER_TRANSPARENT, ssr.LoS.Constant.RENDER_NO_BORDER, ssr.LoS.Constant.RENDER_TRANSPARENT);
            }
            for (var i = this._cullingObstacleObjects.length - 1; i >= 0; i--) {
                var vertexArray = this._cullingObstacleObjects[i].getVertexArray().slice();
                for (var j = vertexArray.length - 1; j >= 0; j--) {
                    vertexArray[j] = this.getParent().convertToNodeSpaceAR(vertexArray[j]);
                }
                render.drawPoly(vertexArray, ssr.LoS.Constant.RENDER_TRANSPARENT, ssr.LoS.Constant.RENDER_NO_BORDER, ssr.LoS.Constant.RENDER_TRANSPARENT);
            }
        }
    },
    setPosition:function(xValue, yValue) {
        if (yValue == undefined) {
            cc.Node.prototype.setPosition.call(this, xValue);
        }
        else {
            cc.Node.prototype.setPosition.call(this, xValue, yValue);
        }
        if (this._maskLayer instanceof cc.Layer) {
            this._maskLayer.updatePosition();
        }
    },
});


ssr.LoS.Component.ShadowMask = cc.LayerColor.extend({
    ctor: function (color, radius) {
        cc.LayerColor.prototype.ctor.call(this, color, radius * 2, radius * 2);
        //
        this.ignoreAnchorPointForPosition(false);
        //
        this._radius = radius;
        this._worldPosition = cc.p(0, 0);
        //
        this._shaderProgram = new cc.GLProgram();
        this._shaderProgram.initWithString(ssr.LoS.Component.ShadowMask.SHADER_VERT, ssr.LoS.Component.ShadowMask.SHADER_FRAG);
        this._shaderProgram.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
        this._shaderProgram.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
        this._shaderProgram.link();
        this._shaderProgram.updateUniforms();
        this.setShaderProgram(this._shaderProgram);
        //
        this.updateUniforms();
    },
    setRadius:function(radius) {
        this.setContentSize(radius * 2, radius * 2);
        this._radius = radius;
        this.updateUniforms();
    },
    updateUniforms:function() {
        this._shaderProgram.use();
        //
        var frameSize = cc.view.getFrameSize();
        var visibleSize = cc.view.getVisibleSize();
        var retinaFactor = cc.view.getDevicePixelRatio();
        var x = this._worldPosition.x * frameSize.width / visibleSize.width * retinaFactor;
        var y = this._worldPosition.y * frameSize.height / visibleSize.height * retinaFactor;
        //
        if (cc.sys.isNative) {
            this.getGLProgramState().setUniformFloat(
                "radius",
                parseFloat(this._radius)
            );
            this.getGLProgramState().setUniformVec2(
                "center",
                cc.p(x, y)
            );
        }
        else {
            this._shaderProgram.setUniformLocationWith1f(
                "radius",
                this._radius
            );
            this._shaderProgram.setUniformLocationF32(
                "center",
                x, y
            );
        }
    },
    updatePosition:function() {
        var center = this.getParent() ? this.getParent().convertToWorldSpace() : cc.p(0, 0);
        if (!cc.pSameAs(center, this._worldPosition)) {
            this._worldPosition = center;
            this.updateUniforms();
        }
    },
});
ssr.LoS.Component.ShadowMask.SHADER_VERT =
        "attribute vec4 a_position;\n"
        + "attribute vec4 a_color;\n"
        + "varying lowp vec4 v_fragmentColor;\n"
        + "void main()\n"
        + "{\n"
        + "    gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;  \n"
        + "    v_fragmentColor = a_color;             \n"
        + "}";

ssr.LoS.Component.ShadowMask.SHADER_FRAG =
        "precision lowp float; \n"
        + "varying vec4 v_fragmentColor; \n"
        + "uniform vec2 center; \n"
        + "uniform float radius; \n"
        + "void main() \n"
        + "{ \n"
        + "float distance = distance(gl_FragCoord.xy, center); \n"
        + "float opacityDelta = v_fragmentColor.a / radius; \n"
        + "float a = v_fragmentColor.a - distance * opacityDelta; \n"
        + "gl_FragColor = vec4(v_fragmentColor.rgb, a); \n"
        + "} ";
